<?php

namespace App\Http\Controllers;

use App\Models\Users;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{

    /**
     * @var Request
     */
    protected $request;


    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function error($error)
    {
        return response()->json(['code' => -1, 'msg' => $error]);
    }

    public function ok($data = [])
    {
        return response()->json(['code' => 0, 'data' => $data]);
    }

    protected function curlPost($url, array $data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    public function userInfo(){
        $token = $this->request->cookie('token');
        if(empty($token)) {
            $token = $this->request->header('token');
        }
        return Users::getByToken($token);
    }

    public function userId(){
        $user = $this->userInfo();
        return $user ? $user->id : 0;
    }

}
